//
//  ForcedUpdatingView.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/4/15.
//

import UIKit
import Reusable
import Localize_Swift
import StoreKit

extension ForcedUpdatingView: NibReusable {}

class ForcedUpdatingView: UIView {
    
    @IBOutlet weak var markView: UIView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var versionLabel: UILabel!
    @IBOutlet weak var submitButton: UIButton!
    @IBOutlet weak var contentLabel: YLLabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        frame = UIScreen.main.bounds
        backgroundColor = UIColor(hex: "000000", 0.5)
        markView.addRoundedCorners(radius: 10)
        contentLabel.alignment = .normal
        contentLabel.lineBreakMode = .byWordWrapping // 按单词换行
        updateLanguageAction()
        
    }
    
    
    var updateContent: String? {
        didSet {
            
            guard let content = updateContent else { return }
            
            let text = NSMutableAttributedString(string: content)
            text.color(UIColor(hex: "333333"))
            text.font(.systemFont(ofSize: 12))
            text.lineSpacing(5)
            contentLabel.attributedText = text
        }
    }
    
    @IBAction func updateAction(_ sender: Any) {
        // UIApplication.sg.openAppStoreUrlWithID(KeyCenter.Apple.id)
        openAppStore()
    }
    
    // 更新语言
    @objc private func updateLanguageAction() {
        titleLabel.text = "更新提醒".localized(.login)
        submitButton.setTitle("确定".localized(), for: .normal)
    }
    
    
    func openAppStore() {
        // 实例化
        let storeVC = SKStoreProductViewController()
        // 设置代理，注意这很重要，否则弹出后没法dismiss了
        storeVC.delegate = self
        // 最后加载应用数据
        storeVC.loadProduct(withParameters: [
            SKStoreProductParameterITunesItemIdentifier: KeyCenter.Apple.id
        ])
        currentViewController()?.present(storeVC)
    }
    
}

extension ForcedUpdatingView: SKStoreProductViewControllerDelegate {
    func productViewControllerDidFinish(_ viewController: SKStoreProductViewController) {
        // 在代理方法里dismiss这个VC
        viewController.dismiss(animated: true)
    }
}
